package com.qingxin.sys.mvc;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;

/**
 * 用于处理String返回类型的转换器，默认编码使用UTF-8
 */
public class StringHttpMessageConverter extends org.springframework.http.converter.StringHttpMessageConverter {
	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
	public static final MediaType TEXT_PLAIN_UTF8 = new MediaType("text", "plain", DEFAULT_CHARSET);
	
	public StringHttpMessageConverter() {
		super();
		
		setWriteAcceptCharset(false);
		
		//设置默认支持的媒体类型
		List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
		supportedMediaTypes.add(TEXT_PLAIN_UTF8);
		supportedMediaTypes.add(MediaType.ALL);
		setSupportedMediaTypes(supportedMediaTypes);
	}
	
	@Override
	protected void writeInternal(String string, HttpOutputMessage outputMessage) throws IOException{
		try {
			MediaType mediaType = outputMessage.getHeaders().getContentType();
			if(mediaType.getCharSet() == null){
				//防乱码处理：如果原有媒体类型中没有指定字符集则使用默认字符集替换
				if("text".equalsIgnoreCase(mediaType.getType()) && "plain".equalsIgnoreCase(mediaType.getSubtype())){
					outputMessage.getHeaders().setContentType(TEXT_PLAIN_UTF8);
				}else{
					MediaType newType = new MediaType(mediaType.getType(), mediaType.getSubtype(), DEFAULT_CHARSET);
					outputMessage.getHeaders().setContentType(newType);
				}
				outputMessage.getHeaders().setContentLength(string.getBytes(DEFAULT_CHARSET).length);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.writeInternal(string, outputMessage);
	}
	
}
